# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class ScrapyDdPipeline:
    def open_spider(self, spider):
        print('---------开始---------')
        self.fp = open('book.test.json', 'a', encoding='utf-8')

    # item就是book对象
    def process_item(self, item, spider):
        # 此方法不推荐 每一个对象都要打开一次文件
        # # 用追加 不能用w覆盖
        # with open('book.test.json', 'a', encoding='utf-8') as fp:
        #     fp.write(str(item))  # 必须是str
        self.fp.write(str(item))
        return item

    def close_spider(self, spider):
        print('-------结束--------')
        self.fp.close()


import urllib.request


# 多条管道同时开启
# 1.定义管道类
# 2.setting开启多个管道
class DDDownloadPipeline:
    def process_item(self, item, spider):
        url = item.get('src')
        filename = './book/' + item.get('name') + '.jpg'
        urllib.request.urlretrieve(url=url, filename=filename)
        return item